<template>
  <div>
    <div class="article-list">
      <van-pull-refresh
        v-model="refreshing"
        @refresh="onRefresh"
        success-text="刷新成功"
      >
        <van-list
          v-model="loading"
          :finished="finished"
          @load="onLoad()"
          finished-text="没有更多了"
        >
          <article-item
            v-for="(item, index) in articles"
            :key="index"
            :article="item"
          ></article-item>
        </van-list>
      </van-pull-refresh>
    </div>
  </div>
</template>

<script>
import ArticleItem from './ArticleItem.vue'
import { getArticles } from '@/api/article'
export default {
  name: 'ArticleList',
  components: { ArticleItem },
  props: {
    channelId: {
      type: Number,
      //   默认是0
      default: 0
    }
  },

  data () {
    return {
      // 正在加载
      loading: false,
      // 数据全部加载完毕
      finished: false,
      // 文章列表
      articles: [],
      // 正在刷新
      refreshing: false,
      //   时间戳
      timestamp: Date.now()
    }
  },
  methods: {
    async onRefresh () {
      //   console.log(this.channelId)
      // 下拉刷新
      // 获取新时间戳
      this.timestamp = Date.now()
      //   发送请求
      const res = await getArticles({
        channel_id: this.channelId,
        timestamp: this.timestamp
      })
      //   console.log(res.data.results)
      //   console.log(res)
      this.finished = false
      this.articles = res.data.results
      console.log(this.articles)
      this.timestamp = res.data.pre_timestamp
      console.log(this.timestamp)
      this.refreshing = false
    },
    async onLoad () {
      // console.log('加载ing')
      // 上拉加载
      try {
        const res = await getArticles({
          channel_id: this.channelId,
          timestamp: this.timestamp
        })
        // console.log(res)

        if (res.data.pre_timestamp) {
          this.timestamp = res.data.pre_timestamp
        } else {
          this.finished = true
        }
        this.articles.push(...res.data.results)
        this.loading = false
      } catch (error) {
        console.dir(error)
        this.$toast.fail('加载失败') // 加载失败
      }
    }
  }
}
</script>

<style scoped lang="less">
.article-list {
  height: 100vh;
  overflow-y: auto;
  padding: 0 16px;
}
</style>
